package com.c2b.algorithm.leetcode.base;

/**
 * <a href="https://leetcode.cn/problems/longest-common-prefix/description/?envType=study-plan-v2&envId=top-interview-150">最长公共前缀(Longest Common Prefix)</a>
 * <p>编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：strs = ["flower","flow","flight"]
 *      输出："fl"
 *
 * 示例 2：
 *      输入：strs = ["dog","racecar","car"]
 *      输出：""
 *      解释：输入不存在公共前缀。
 * </pre>
 * </p>
 * <b>提示：</b>
 * <ul>
 *     <li>1 <= strs.length <= 200</li>
 *     <li>0 <= strs[i].length <= 200</li>
 *     <li>strs[i] 仅由小写英文字母组成</li>
 * </ul>
 *
 * @author c2b
 * @since 2023/10/10 14:48
 */
public class LC0014LongestCommonPrefix_S {

    static class Solution {
        public String longestCommonPrefix(String[] strs) {
            if (strs == null || strs.length == 0) {
                return "";
            }
            for (int charIndex = 0; charIndex < strs[0].length(); charIndex++) {
                char currChar = strs[0].charAt(charIndex);
                // strs数组里面的字符串
                for (String str : strs) {
                    // strs[i].length()：当前字符串的长度。
                    // 1.strs[i].length()==charIndex：当前字符串无字符了
                    // 2.当前字符串在当前位置的字符与要求的字符currChar不相等
                    if (str.length() == charIndex || str.charAt(charIndex) != currChar) {
                        return strs[0].substring(0, charIndex);
                    }
                }
            }
            return strs[0];
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.longestCommonPrefix(new String[]{"flower", "flow", "flight"}));
        System.out.println(solution.longestCommonPrefix(new String[]{"dog","racecar","car"}));
        System.out.println(solution.longestCommonPrefix(new String[]{"a","ab"}));
    }
}
